#include <avr/io.h>
#include <util/delay.h>

#define PORT PORTD 
#define SC_CLOCK 2
#define SC_DATA 3
#define SC_RESET 4

void SmartCard_Reset()
{
	DDRD |= (1<< SC_CLOCK) | (1<<SC_RESET);
	DDRD &= ~(1<<SC_DATA);


	PORT |= (1<<SC_RESET);

	_delay_ms(10);

	PORT |= (1<<SC_RESET) | (1<< SC_CLOCK);

	_delay_ms(10);

	PORT &= ~(1<< SC_CLOCK);

	_delay_ms(10);

	PORT &= ~( (1<<SC_RESET) );
	
	_delay_ms(10);
}

void SmartCard_Start()
{
	DDRD |= (1<<SC_CLOCK) | (1<<SC_DATA);

	PORT |= (1<<SC_DATA);
	_delay_ms(1);

	PORT |= (1<< SC_CLOCK) | (1<<SC_DATA);
	_delay_ms(1);

	PORT &= ~(1<<SC_DATA);
	_delay_ms(1);

	PORT &= ~(1<<SC_CLOCK);
	_delay_ms(1);

}

void SmartCard_Stop()
{
	DDRD |= (1<<SC_CLOCK) | (1<<SC_DATA);

	PORT &= ~(1<<SC_DATA);
	_delay_ms(1);

	PORT |= (1<<SC_CLOCK);
	_delay_ms(1);

	PORT |= (1<< SC_CLOCK) | (1<<SC_DATA);
	_delay_ms(1);

	PORT &= ~(1<<SC_CLOCK);
	_delay_ms(1);

}


unsigned char SmartCard_ReadByte()
{
	DDRD |= (1<< SC_CLOCK);
	DDRD &= ~(1<<SC_DATA);

	unsigned c=0;
	for(int i=0;i<8;i++)
	{
	    c>>=1;

		PORT |= (1<< SC_CLOCK) | (1<<SC_DATA);
		_delay_ms(1);

		if ( PIND & (1<<SC_DATA) )
		{
			c |=128;
		}

		PORT &= ~(1<< SC_CLOCK);
		_delay_ms(1);
	}

	return c;
}

void SmartCard_WriteBit(unsigned char v)
{
	if ( v >0 )
	{
		PORT |= (1<< SC_DATA);
	}
	else
	{
		PORT &= ~(1<< SC_DATA);
	}
	_delay_ms(1);

	PORT |= (1<< SC_CLOCK);

	_delay_ms(1);

	PORT &= ~(1<< SC_CLOCK);

	PORT &= ~(1<< SC_DATA);

	_delay_ms(1);
}


void SmartCard_WriteByte(unsigned char v)
{
	DDRD |= (1<< SC_CLOCK) | (1<<SC_DATA);

	//sync
	//SmartCard_WriteBit( 0 );

	//char ones = 0;

	for(char i=0;i<8;i++)
	{
		SmartCard_WriteBit( v & 128 );
/*
		if ( v & 128 )
		{
			ones++;
		}
*/
		v<<=1;
	}

	//send parity bit
	//SmartCard_WriteBit( ones & 1 );

	//_delay_ms(5);

}
